<template>
  <el-dialog :title="title" v-model="dialogVisible" width="600px" append-to-body destroy-on-close>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input v-model="form.employeeName" placeholder="请输入员工姓名" />
      </el-form-item>
      <el-form-item label="考勤日期" prop="attendanceDate">
        <el-date-picker
          v-model="form.attendanceDate"
          type="date"
          placeholder="选择考勤日期"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="上班打卡时间" prop="clockInTime">
        <el-time-picker
          v-model="form.clockInTime"
          placeholder="选择上班打卡时间"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="上班打卡地点" prop="clockInAddress">
        <el-input v-model="form.clockInAddress" placeholder="请输入上班打卡地点" />
      </el-form-item>
      <el-form-item label="下班打卡时间" prop="clockOutTime">
        <el-time-picker
          v-model="form.clockOutTime"
          placeholder="选择下班打卡时间"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="下班打卡地点" prop="clockOutAddress">
        <el-input v-model="form.clockOutAddress" placeholder="请输入下班打卡地点" />
      </el-form-item>
      <el-form-item label="考勤状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择考勤状态" style="width: 100%">
          <el-option
            v-for="option in STATUS_OPTIONS"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤规则" prop="ruleId">
        <el-select v-model="form.ruleId" placeholder="请选择考勤规则" style="width: 100%">
          <el-option
            v-for="rule in ruleOptions"
            :key="rule.ruleId"
            :label="rule.ruleName"
            :value="rule.ruleId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
          :rows="3"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import type { AttendanceRecordVO, AttendanceRecordForm } from "@/types/attendance/record";
import { STATUS_OPTIONS, AttendanceStatus } from "@/types/attendance/record";
import { addAttendanceRecord, updateAttendanceRecord } from "@/api/attendance/record";
import { getRuleList } from "@/api/attendance/rule";

const props = defineProps<{
  title: string;
  record?: AttendanceRecordVO;
  modelValue: boolean;
}>();

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}>();

// 表单ref
const formRef = ref<FormInstance>();

// 考勤规则选项
const ruleOptions = ref<Array<{ ruleId: number; ruleName: string }>>([]);

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val)
});

// 表单对象
const form = reactive<AttendanceRecordForm>({
  employeeId: 0,
  employeeName: "",
  attendanceDate: "",
  clockInTime: "",
  clockInAddress: "",
  clockOutTime: "",
  clockOutAddress: "",
  ruleId: 0,
  status: AttendanceStatus.NORMAL,
  remark: ""
});

// 表单校验规则
const rules = {
  employeeName: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
  attendanceDate: [{ required: true, message: "请选择考勤日期", trigger: "change" }],
  clockInTime: [{ required: true, message: "请选择上班打卡时间", trigger: "change" }],
  clockOutTime: [{ required: true, message: "请选择下班打卡时间", trigger: "change" }],
  status: [{ required: true, message: "请选择考勤状态", trigger: "change" }],
  ruleId: [{ required: true, message: "请选择考勤规则", trigger: "change" }]
};

// 监听编辑状态
watch(
  () => props.record,
  record => {
    if (record) {
      Object.assign(form, record);
    } else {
      Object.assign(form, {
        employeeId: 0,
        employeeName: "",
        attendanceDate: "",
        clockInTime: "",
        clockInAddress: "",
        clockOutTime: "",
        clockOutAddress: "",
        ruleId: 0,
        status: AttendanceStatus.NORMAL,
        remark: ""
      });
    }
  },
  { immediate: true }
);

// 获取考勤规则列表
const getAttendanceRules = async () => {
  try {
    const res = await getRuleList({ pageNum: 1, pageSize: 100 });
    ruleOptions.value = res.data.rows.map(rule => ({
      ruleId: Number(rule.ruleId),
      ruleName: rule.ruleName
    }));
  } catch (error) {
    console.error("获取考勤规则列表失败:", error);
  }
};

// 表单提交
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async valid => {
    if (valid) {
      try {
        if (form.recordId) {
          await updateAttendanceRecord(form);
        } else {
          await addAttendanceRecord(form);
        }
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        emit("success");
      } catch (error) {
        console.error("保存考勤记录失败:", error);
      }
    }
  });
};

// 取消按钮
const cancel = () => {
  dialogVisible.value = false;
  reset();
};

// 表单重置
const reset = () => {
  formRef.value?.resetFields();
};

// 组件挂载时获取考勤规则列表
onMounted(() => {
  getAttendanceRules();
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
  padding-top: 20px;
  margin-right: 16px;
}
</style>
